<template>
  <view class="content" :class="'theme-'+theme">
	<view class="addTitle">
		<view class="titleDetail">
			<view class="titleLeft" >
				<image src="../../static/newh5/fanhui.png"
				class="yticon"
				style="width: 13px;height: 20px;color:black"
				@click="returnIndex()"
				></image>
			</view>
			<view class="titleCenter" >
			<b class="titleText">{{bartitle}}</b>
			</view>
			<view class="titleRight"  style="color: #269cd3;flex:1" > </view>
		</view>
		</view>
    <view class="row b-b">
      <text class="tit">联系人</text>
      <input class="input" type="text" v-model="addressData.consigneeName" placeholder="收货人姓名" placeholder-class="placeholder" />
    </view>
    <view class="row b-b">
      <text class="tit">手机号</text>
      <input class="input" type="number" v-model="addressData.mobile" placeholder="收货人手机号码" placeholder-class="placeholder" />
    </view>
    <view class="row b-b">
      <text class="tit">邮箱</text>
      <input class="input" type="text" v-model="addressData.email" placeholder="收货人邮箱" placeholder-class="placeholder" />
    </view>
    <view class="row b-b">
      <text class="tit">地址</text>
      <!-- 			<text @click="chooseLocation" class="input">
        {{addressData.areaName}}
      </text> -->
      <view class="input" @click="toggleTab">{{(addressData.areaName===null||addressData.areaName===''||addressData.areaName===undefined)?'请选择收货地址':addressData.areaName}}</view>
      <uni-popup ref="popup" type="bottom">
        <view class="popup">
          <view class="picker-btn">
            <view class="left" @click="cancel">取消</view>
            <view class="right" @click="confirm">确定</view>
          </view>
          <picker-view :indicator-style="indicatorStyle" :value="valueArr" @change="bindChange">
            <picker-view-column>
              <view class="item" v-for="(item,index) in province" :key="index">{{item.name}}</view>
            </picker-view-column>
            <picker-view-column>
              <view class="item" v-for="(item,index) in province[valueArr[0]].children" :key="index">{{item.name}}</view>
            </picker-view-column>
            <picker-view-column>
              <view class="item" v-for="(item,index) in province[valueArr[0]].children[valueArr[1]].children" :key="index">{{item.name}}</view>
            </picker-view-column>
            <picker-view-column>
              <view class="item" v-for="(item,index) in province[valueArr[0]].children[valueArr[1]].children[valueArr[2]].children" :key="index">{{item.name}}</view>
            </picker-view-column>
          </picker-view>
        </view>
      </uni-popup>
      <!-- <text class="yticon icon-shouhuodizhi"></text> -->
    </view>
    <view class="row b-b">
      <text class="tit">详细地址</text>
      <input class="input" type="text" v-model="addressData.addr" placeholder="楼号、门牌" placeholder-class="placeholder" />
    </view>

    <view class="row default-row" v-if="manageType==='edit'">
      <text class="tit">设为默认</text>
      <switch :disabled="isDefault" :checked="addressData.isDefault" :color="themeColor" @change="switchChange" />
    </view>
    <button class="add-btn   themeBgColor" @click="submit">提交</button>
  </view>
</template>

<script>
import {  goback } from "@/common/utils/navigateBack.js";
import {
  setDefault,
  updateAddr,
  addAddr,
  loadAddr,
  loadChildAddr,
  deleteAddr
} from '../../api/order/order.js'
export default {
  data() {
    return {
      bartitle:'新增收货地址',
      addressData: {
        consigneeName: '',
        mobile: '',
        areaId: '',
        areaName: '',
        addr: '',
        isDefault: false,
        email: ''
      },
      isDefault: false,
      addressStatus: false,
      manageType: '',
      province: [],
      city: [],
      area: [],
      visible: false,
      multiIndex: 0,
      indicatorStyle: `height: ${Math.round(uni.getSystemInfoSync().screenWidth/(750/100))}px;`,
      valueArr: [0, 0, 0,0], //用于判断当前滑动的那一列
      areaId: '',
    }
  },
  onLoad(options) {
    console.log('option',JSON.parse(options.data) );
    let option = JSON.parse(options.data)
    let title = '新增收货地址';
    if (option.type === 'edit') {
      title = '编辑收货地址'
      this.addressData = option.item
      this.isDefault = this.addressData.isDefault
    }
    this.manageType = option.type;
    this.bartitle = title
    // uni.setNavigationBarTitle({
    //   title
    // })
    this.initLoadArea()
  },
  methods: {
			returnIndex() {
				goback()
			},
    bindChange(e) {
      const val = e.detail.value;
      if (this.valueArr[0] !== val[0]) {
        this.loadCity(this.province[val[0]].id)
      } else if (this.valueArr[1] !== val[1]) {
        this.loadArea(this.province[val[0]].children[val[1]].id,1)
      }
      else if (this.valueArr[2] !== val[2]) {
        this.loadArea(this.province[val[0]].children[val[1]].children[val[2]].id,2)
      }
      this.valueArr = val
    },
    initLoadArea() {
      loadAddr().then(res => {
        if (res.code === 0) {
          this.province = res.data;
          this.loadCity(this.province[0].id)
        } else {
          this.toast(res.message)
        }
      })
    },
    loadCity(parentId) {
      const params = {
        parentId: parentId
      }
      loadChildAddr(params).then(res => {
        if (res.code === 0) {
          this.city = res.data;
          if (!this.province[this.valueArr[0]].children||this.province[this.valueArr[0]].children.length===0) {
            this.$set(this.province[this.valueArr[0]], 'children', [])
            res.data.forEach(item => {
              this.province[this.valueArr[0]].children.push(item)
            })
            this.loadArea(this.province[this.valueArr[0]].children[this.valueArr[1]].id,1)
            //this.loadArea(this.province[this.valueArr[0]].children[this.valueArr[1]].children[this.valueArr[2]].id,2)
          }
        } else {
          this.toast(res.message)
        }
      })
    },
    loadArea(parentId,level) {
      const params = {
        parentId: parentId
      }
      loadChildAddr(params).then(res => {
        if (res.code === 0) {
          this.area = res.data;
          if(level===1)
          {
            if (!this.province[this.valueArr[0]].children[this.valueArr[1]].children||this.province[this.valueArr[0]].children[this.valueArr[1]].children.length===0) {
              this.$set(this.province[this.valueArr[0]].children[this.valueArr[1]], 'children', [])
              res.data.forEach(item => {
                this.province[this.valueArr[0]].children[this.valueArr[1]].children.push(item)
              })
            }
            this.loadArea(this.province[this.valueArr[0]].children[this.valueArr[1]].children[this.valueArr[2]].id,2);
          }
          else if(level===2)
          {
            if (!this.province[this.valueArr[0]].children[this.valueArr[1]].children[this.valueArr[2]].children||this.province[this.valueArr[0]].children[this.valueArr[1]].children[this.valueArr[2]].children.length===0) {
              this.$set(this.province[this.valueArr[0]].children[this.valueArr[1]].children[this.valueArr[2]], 'children', [])
              res.data.forEach(item => {
                this.province[this.valueArr[0]].children[this.valueArr[1]].children[this.valueArr[2]].children.push(item)
              })
            }
          }
        } else {
          this.toast(res.message)
        }
      })
    },
    toggleTab() {
      this.$refs.popup.open();
    },
    cancel() {
      this.$refs.popup.close();
    },
    confirm() {
      this.$refs.popup.close();
      let children=this.province[this.valueArr[0]].children[this.valueArr[1]].children[this.valueArr[2]].children
      if(children && children.length>0){
        this.addressData.areaName = this.province[this.valueArr[0]].name + '/' + this.province[this.valueArr[0]].children[
                this.valueArr[1]].name +
            '/' +
            this.province[this.valueArr[0]].children[this.valueArr[1]].children[this.valueArr[2]].name+
            '/' +children[this.valueArr[3]].name

        this.areaId = children[this.valueArr[3]].id;
      }
      else{
        this.addressData.areaName = this.province[this.valueArr[0]].name + '/' + this.province[this.valueArr[0]].children[
                this.valueArr[1]].name +
            '/' +
            this.province[this.valueArr[0]].children[this.valueArr[1]].children[this.valueArr[2]].name

        this.areaId = this.province[this.valueArr[0]].children[this.valueArr[1]].children[this.valueArr[2]].id;
      }
    },
    switchChange(e) {
      if (!this.isDefault)
        this.addressData.isDefault = e.detail.value;
    },
    //地图选择地址
    chooseLocation() {
      uni.chooseLocation({
        success: (data) => {
          this.addressData.areaName = data.name;
          // this.addressData.areaName = data.name;
        }
      })
    },
    toast(msg) {
      uni.showToast({
        title: msg,
        duration: 1200,
        mask: false,
        icon: 'none'
      });
    },
    setDefaultAddr() {
      const params = {
        id: this.addressData.id
      }
      setDefault(params).then(res => {
        if (res.code === 0) {} else {
          this.toast(res.message)
          this.addressData.isDefault = false
        }
      })
    },
    back() {
      setTimeout(() => {
        // uni.navigateBack()
        this.backRouter()
      }, 800)
    },
    backRouter() {
                // #ifdef H5
        let canBack = true
        const pages = getCurrentPages()
                // 有可返回的页面则直接返回，uni.navigateBack默认返回失败之后会自动刷新页面 ，无法继续返回
        if (pages.length > 1) {
                    uni.navigateBack(1)
                    return;
        }
                // vue router 可以返回uni.navigateBack失败的页面 但是会重新加载
        let a = this.$router.go(-1)
                // router.go失败之后则重定向到首页
        if (a == undefined) {
                    uni.reLaunch({
                        url: "/pages/index/index"
                    })
        }
        return;
                // #endif
                uni.navigateBack(1)
      },
    //提交
    submit() {
      const param = {
        id: this.addressData.id
      }
      let data = this.addressData;
      if (!data.consigneeName) {
        this.$api.msg('请填写收货人姓名');
        return;
      }
      if (!/(^1[3|4|5|7|8][0-9]{9}$)/.test(data.mobile)) {
        this.$api.msg('请输入正确的手机号码');
        return;
      }
      if (!/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(data.email)) {
        this.$api.msg('请输入正确的邮箱');
        return;
      }
      if (!data.areaName) {
        this.$api.msg('请选择收货地址');
        return;
      }
      if (!data.addr) {
        this.$api.msg('请填写详细地址');
        return;
      }
      if (this.addressStatus){
        return;
      }
      this.addressStatus = true
      if (this.manageType === 'edit') {
        const params = {
          id: this.addressData.id,
          consigneeName: this.addressData.consigneeName,
          areaId: this.areaId,
          areaName: this.addressData.areaName,
          addr: this.addressData.addr,
          mobile: this.addressData.mobile,
          email: this.addressData.email,
        }
        updateAddr(params).then(res => {
          if (res.code === 0) {
            this.$api.msg(`地址${this.manageType==='edit' ? '修改': '添加'}成功`);
            if (data.isDefault && !this.isDefault) {
              setDefault(param).then(res => {
                if (res.code === 0) {
                  this.$api.prePage().refreshList();
                  this.back()
                } else {
                  this.toast(res.message)
                  this.addressData.isDefault = false
				  this.$api.prePage().refreshList();
                  this.back()
                }
              })
            } else {
              this.$api.prePage().refreshList();
              this.back()
            }
          } else {
            this.toast(res.message)
          }
        })
      } else if (this.manageType === 'add') {
        let par = {
          id: this.areaId,
          consigneeName: this.addressData.consigneeName,
          areaId: this.areaId,
          areaName: this.addressData.areaName,
          addr: this.addressData.addr,
          mobile: this.addressData.mobile,
          email: this.addressData.email,
        }
        addAddr(par).then(res => {
          if (res.code === 0) {
            //this.$api.prePage()获取上一页实例，可直接调用上页所有数据和方法，在App.vue定义
            this.$api.msg(`地址${this.manageType==='edit' ? '修改': '添加'}成功`);

            if (!uni.getStorageSync('areaId')) {
              uni.setStorageSync('areaId', this.areaId)
            }
            // if (data.isDefault && !this.isDefault) {
            // 	setDefault(param).then(res => {
            // 		if (res.code === 0) {
            // 			this.$api.prePage().refreshList();
            // 			this.back()
            // 		} else {
            // 			this.toast(res.message)
            // 			this.addressData.isDefault = false
            // 			this.back()
            // 		}
            // 	})
            // } else {
            this.$api.prePage().refreshList();
            this.back()
            // }
          } else {
            this.toast(res.message)
          }
        })
      }
    },
  }
}
</script>

<style lang="scss">
page {
  background: $page-color-base;
  padding-top: 16upx;
}

.popup {
  height: fit-content;
  width: 100%;
  background: #fff;
}

.picker-btn {
  display: flex;
  height: 100upx;
  width: 100%;
  line-height: 100upx;
  background: #fff;
  font-size: 34upx;
  z-index: 1;
  border-bottom: 1rpx solid #ccc;

  .left {
    flex: 1;
    color: #0076FF;
    padding-left: 40upx;
    box-sizing: border-box;
  }

  .right {
    flex: 1;
    text-align: right;
    padding-right: 40upx;
    color: #FE4533;
    box-sizing: border-box;
  }
}

picker-view {
  width: 100%;
  height: 500rpx;
  display: relative;
}

.item {
  line-height: 100rpx;
  text-align: center;
}

.row {
  display: flex;
  align-items: center;
  position: relative;
  padding: 0 30upx;
  height: 110upx;
  background: #fff;

  .tit {
    flex-shrink: 0;
    width: 140upx;
    font-size: 30upx;
    color: $font-color-dark;
  }

  .delete {
    flex-shrink: 0;
    width: 120upx;
    font-size: 30upx;
    color: #fa436a;
  }

  .input {
    flex: 1;
    font-size: 30upx;
    color: $font-color-dark;
  }

  .icon-shouhuodizhi {
    font-size: 36upx;
    color: $font-color-light;
  }
}

.default-row {
  margin-top: 16upx;

  .tit {
    flex: 1;
  }

  switch {
    transform: translateX(16upx) scale(.9);
  }
}

.add-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 690upx;
  height: 80upx;
  margin: 60upx auto;
  font-size: $font-lg;
  color: #fff;
  // background-color: $my-newh5-color;
  border-radius: 10upx;
  // box-shadow: 1px 2px 5px rgba(219, 63, 96, 0.4);
}
</style>
